package com.etlmaster.executor.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.StringUtils;

import com.etlmaster.executor.utils.DataCollectionUtils;
import com.etlmaster.executor.utils.LogWriter;

/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
public class BteqUtil {
	private static final String UNIT = "<";
	public static final String SUCCESS = "success";
	public static final String FAULT = "fault";

	public String doExecute(String cmd) {
		String btedDir = DataCollectionUtils.getProperties("bteqHome");
		if (StringUtils.isEmpty(btedDir)) {
			LogWriter.addLog("ERROR", "找不到bteqHome配置");
			return FAULT;
		}
		if (StringUtils.isEmpty(cmd)) {
			LogWriter.addLog("ERROR", "执行命令为空！");
			return FAULT;
		}
		StringBuffer exeCmd = new StringBuffer(btedDir).append(UNIT).append(cmd);
		File f = null;
		try {
			//String logPath = DpExecutorUtils.getLogPath();
			String logPath=System.getProperty("java.io.tmpdir");
			f = writeToFile(exeCmd.toString(), "sh", logPath);
			LogWriter.addLog("DEBUG", "开始执行本地命令({})", exeCmd.toString());
			f.setExecutable(true);
			Shell.ShellCommandExecutor executor = new Shell.ShellCommandExecutor(new String[] { f.getPath() });
			executor.execute();
			LogWriter.addLog("INFO", "执行脚本返回值：[{}],返回结果：[{}]", String.valueOf(executor.getExitCode()),
					executor.getOutput());
			return SUCCESS;
		} catch (IOException e) {
			LogWriter.addLog("ERROR", "本地命令({})执行错误 ({})", exeCmd.toString(), e.getMessage());
			return FAULT;
		}finally{
			LogWriter.addLog("DEBUG","清除脚本文件 " + f.getAbsolutePath() + (f.delete()?"成功":"失败")) ;
		}
	}

	public File writeToFile(String content, String suff, String parentPath) throws IOException {
		int i = 0;
		File f = new File(parentPath,
				new Date().getTime() + "_" + i + "_" + this.hashCode() + content.hashCode() + "." + suff);
		while (f.exists()) {
			f = new File(parentPath,
					new Date().getTime() + "_" + (++i) + "_" + this.hashCode() + content.hashCode() + "." + suff);
		}
		f.createNewFile();
		FileOutputStream fos = new FileOutputStream(f);
		fos.write(content.toString().getBytes("UTF-8"));
		fos.close();
		return f;
	}

	public String getIP(String url) {
		/**
		 * 判断IP格式和范围
		 */
		String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
		return matchResult(url, rexp);
	}

	private String matchResult(String str, String reg) {
		Pattern p = Pattern.compile(reg);
		Matcher m = p.matcher(str);
		if (m.find()) {
			return m.group(0);
		} else {
			return "";
		}
	}

}
